let pageNum = 1;
let pageSize = 10;

function readerPages(total) {
    const pageContainer = document.getElementById('page-container');
    pageContainer.innerHTML = '';

    let count = Math.ceil(total / pageSize);
    
    for (let i = 0;i < count;i++) {
      let page = document.createElement('a');
      if (pageNum == i + 1) {
          page.className = 'active'
      }
      page.innerHTML = i + 1
      page.onclick = () => {
        pageNum = i + 1;
        getVideoList();
      }
      pageContainer.appendChild(page)

    }
}

function readerList(videos) {
    const videoList = document.getElementById('video-list');
    videoList.innerHTML = '';

    videos.forEach(video => {
        const card = document.createElement('div');
        card.className = 'video-card';
        card.innerHTML = `
            <a class="edit-btn" onclick="javascript:void(0)" href="/edit.html?v=${encodeURIComponent(video.url)}">编辑</a>
            <video class='video-player' src="${video.url}" preload="metadata" muted ></video>
            <div class="video-list-title">${video.name}</div>
        `;
        card.onclick = (e) => {
            e.stopPropagation();

            window.location.href = `/player.html?v=${encodeURIComponent(video.url)}`;
        };
        videoList.appendChild(card);
    });
}

function getVideoList() {
    fetch(`/api/files?size=${pageSize}&page=${pageNum}`)
    .then(response => response.json())
    .then(data => {
        let total = data.total;
        let videos = data.list;

        readerList(videos);
        readerPages(total);

    })
    .catch(error => console.error('加载失败:', error));
}

document.addEventListener('DOMContentLoaded', () => {
    getVideoList();

});

function refreshServer() {
  fetch('/api/fresh')
    .then(response => response.json())
    .then(data => {
      console.log(data.message);
      // 刷新页面
      location.reload();
    })
    .catch(error => console.error('刷新失败:', error));
}
